import json
import logging

from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.views import View
from django_redis import get_redis_connection
from django import http
from django.db import DatabaseError
from django.urls import reverse
from django.contrib.auth import login, authenticate, logout
import re

from celery_tasks.Email.tasks import send_verify_email
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from users import constants
from users.models import User, Address
from meiduo_mall.utils.response_code import RETCODE
from users.utils import generate_verify_email_url, check_verify_email_token

logger = logging.getLogger('django')


# Create your views here.

class UsernameCountView(View):
    """ 判断用户是否重复注册 """

    def get(self, request, username):
        """
        :param username: 用户名
        :return: JSON
        """
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """ 判断用户手机号是否重复注册 """

    def get(self, request, mobile):
        """
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    """ 用户注册 """

    def get(self, request, register_errmsg=None):
        """ 返回注册界面 """
        if register_errmsg is None:
            return render(request, 'register.html')
        return render(request, 'register.html', {'register_errmsg': register_errmsg})

    def post(self, request):
        """ 用户注册业务逻辑 """
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        Email = request.POST.get('Email')
        Email_code = request.POST.get('Email_code')
        allow = request.POST.get('allow')

        # 判断参数是否齐全
        if not all([username, password, password2, mobile, Email, Email_code, allow]):
            return http.HttpResponseForbidden('缺少关键参数')
        # 判断用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断邮箱格式
        if not re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', Email):
            return http.HttpResponseForbidden('请输入正确的邮箱')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        redis_conn = get_redis_connection('verify_code')
        Email_code_server = redis_conn.get(f'Email_{Email}')
        if Email_code_server is None:
            return self.get(request, '验证码已失效')
        if Email_code_server.decode() != Email_code:
            return self.get(request, '邮箱验证码不正确')
        redis_conn.delete(f'Email_{Email}')

        # 保存用户数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile, email=Email)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 状态保持  成功即登陆
        login(request, user)
        res = redirect(reverse('contents:index'))
        res.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return res


class LoginView(View):
    """ 用户登陆 """

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return http.HttpResponseForbidden('缺少关键参数')
        # 判断用户名
        if not (re.match(r'^[a-zA-Z0-9_-]{5,20}$', username) or \
                re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', username)):
            return http.HttpResponseForbidden('请输入正确的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')

        # 用户认证
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'accout_errmsg': '账号或密码错误'})

        login(request, user)  # 状态保持
        # remembered 确定状态保持周期
        if remembered == 'on':
            request.session.set_expiry(None)  # None默认 保持2周
        else:
            request.session.set_expiry(0)  # 浏览器退出销毁

        next = request.GET.get('next')
        if next:
            res = redirect(next)
        else:
            res = redirect(reverse('contents:index'))
        # 有效期15天
        res.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return res


class LogoutView(View):
    """ 用户退出登陆 """

    def get(self, request):
        logout(request)
        res = redirect(reverse('contents:index'))
        res.delete_cookie('username')
        return res


class UserInfoView(LoginRequiredMixin, View):
    """ 用户中心 """

    def get(self, request):
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active,
        }
        return render(request, 'user_center_info.html', context)


class EmailView(LoginRequiredJSONMixin, View):
    """ 添加/更改邮箱 """

    def put(self, request):
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        email = json_dict.get('email')
        if not re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email):
            return http.HttpResponseForbidden('参数email错误')
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})

        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class VerifyEmailView(View):
    """ 验证邮箱 """

    def get(self, request):
        token = request.GET.get('token')

        if not token:
            return http.HttpResponseForbidden('缺失token参数')
        user = check_verify_email_token(token)
        if not user:
            return http.HttpResponseForbidden('无效的token')

        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('激活邮箱失败')

        return redirect(reverse('users:info'))


class AddressView(LoginRequiredMixin, View):
    """ 用户收货地址 """

    def get(self, request):
        """ 查询 """

        login_user = request.user
        addresses = Address.objects.filter(user=login_user, is_deleted=False)

        address_dict_list = []
        for address in addresses:
            address_dict = address.to_json()
            address_dict_list.append(address_dict)

        context = {
            "default_address_id": login_user.default_address_id,
            "addresses": address_dict_list
        }
        return render(request, 'user_center_site.html', context)


class AddressCreateView(LoginRequiredMixin, View):
    """ 用户新增收货地址 """

    def post(self, request):
        """ 新增地址 """

        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 第一个添加的地址设为默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = address.to_json()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})


class UpdateDestroyAddressView(LoginRequiredMixin, View):
    """ 修改和删除地址 """

    def put(self, request, address_id):
        """ 修改地址 """
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        try:
            Address.objects.filter(user=request.user, id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})

        # 更新成功 - 返回响应信息
        address = Address.objects.filter(user=request.user, id=address_id).first()
        address_dict = address.to_json()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """ 删除地址 """
        try:
            address = Address.objects.filter(user=request.user, id=address_id).first()
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredMixin, View):
    """ 设置默认地址 """

    def put(self, request, address_id):

        try:
            address = Address.objects.get(user=request.user, id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredMixin, View):
    """ 设置地址标题 """

    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            address = Address.objects.get(user=request.user, id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})
